/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.rest.front;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.zhengjie.annotation.AnonymousAccess;
import me.zhengjie.annotation.Log;
import me.zhengjie.annotation.rest.AnonymousGetMapping;
import me.zhengjie.modules.system.bo.req.DccUpdateUserReq;
import me.zhengjie.modules.system.domain.DccUser;
import me.zhengjie.modules.system.service.DccUserService;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.dto.DccUserDto;
import me.zhengjie.modules.system.service.dto.DccUserQueryCriteria;
import me.zhengjie.utils.RedisUtils;
import me.zhengjie.utils.SmsAliUtils;
import me.zhengjie.utils.StringUtils;
import me.zhengjie.utils.bo.MllSms;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
* @website https://eladmin.vip
* @author cjl
* @date 2023-05-16
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "DCC客户关系相关管理")
@RequestMapping("/front/dccUser")
public class FrontDccUserController {



    private final DccUserService dccUserService;

    private final RedisUtils redisUtils;

    public static final String MLL_BUCKETNAME_LINE = "wb.user.cai";


    @GetMapping("/sendAlert")
    @AnonymousAccess
    @ApiOperation(value = "发送动码", httpMethod = "GET")
    public ResponseEntity<Object> sendAlert(HttpServletRequest request, String phone) {
        int code = (int) ((Math.random() * 9 + 1) * 100000);
        redisUtils.set(MLL_BUCKETNAME_LINE+phone,code,30, TimeUnit.MINUTES);
        MllSms mllSms = SmsAliUtils.sendAlert("1135171", phone, code+"", "ds");
        return new ResponseEntity<>("发送成功",HttpStatus.OK);
    }

    @Log("客户注册")
    @ApiOperation("客户注册")
    @AnonymousAccess
    @GetMapping(value = "/register")
    public ResponseEntity<Object> register(@RequestParam(value = "phone",required = true) String phone,@RequestParam(value = "code",required = true)  String code,@RequestParam(value = "password",required = false) String password) throws IOException {
        Object o = redisUtils.get(MLL_BUCKETNAME_LINE + phone);
        if (o.toString().equals(code)){
            DccUser dccUser=new DccUser();
            dccUser.setNickName(phone);
            dccUser.setPasswod(StringUtils.isEmpty(password)?"123456":password);
            dccUser.setPhone(phone);
            dccUser.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
            dccUser.setCreatedAt(new Timestamp(System.currentTimeMillis()));
            dccUserService.create(dccUser);
            return new ResponseEntity<>("注册成功",HttpStatus.OK);
        }else{
            return new ResponseEntity<>("注册失败!",HttpStatus.BAD_GATEWAY);
        }
    }
    @Log("客户重置密码")
    @ApiOperation("客户重置密码")
    @AnonymousAccess
    @GetMapping(value = "/resettingPassword")
    public ResponseEntity<Object> resettingPassword(@RequestParam(value = "phone",required = true) String phone,@RequestParam(value = "code",required = true)  String code,@RequestParam(value = "password",required = false) String password) throws IOException {
            Object o = redisUtils.get(MLL_BUCKETNAME_LINE + phone);
        if (o.toString().equals(code)){
            DccUserQueryCriteria dccUserQueryCriteria = new DccUserQueryCriteria();
            dccUserQueryCriteria.setPhone(phone);
            List<DccUserDto> dccUserDtos = dccUserService.queryAll(dccUserQueryCriteria);
            if (CollectionUtils.isEmpty(dccUserDtos)){
                return new ResponseEntity<>("客户不存在，重置失败!",HttpStatus.BAD_GATEWAY);
            }else{
                DccUserDto dccUserDto = dccUserDtos.get(0);
                DccUser dccUser=new DccUser();
                BeanUtil.copyProperties(dccUserDto,dccUser);
                dccUser.setPasswod(password);

                dccUser.setUpdatedAt(new Timestamp(System.currentTimeMillis()));

                dccUser.setUpdatedAt(new Timestamp(System.currentTimeMillis()));

                dccUserService.update(dccUser);
            }

            return new ResponseEntity<>("重置成功",HttpStatus.OK);
        }else{
            return new ResponseEntity<>("重置失败!",HttpStatus.BAD_GATEWAY);
        }

    }

    @Log("修改用户信息")
    @ApiOperation("修改用户信息")
    @PostMapping(value = "/updateUserInfo")
    @AnonymousAccess
    public ResponseEntity<Object> updateUserInfo(@Validated @RequestBody DccUpdateUserReq dccUpdateUserReq) throws Exception {
             DccUserDto byId = dccUserService.findById(StpUtil.getLoginIdAsInt());
             if(byId==null||StringUtils.isAllEmpty(byId.getPhone())){
                 return new ResponseEntity<>("请先登录",HttpStatus.UNAUTHORIZED);
             }
             DccUser dccUser=new DccUser();
             BeanUtil.copyProperties(byId,dccUser);
            Class<? extends DccUpdateUserReq> aClass = dccUpdateUserReq.getClass();
            Class<? extends DccUser> aClass1 = dccUser.getClass();
            Field[] fields = aClass.getDeclaredFields();
            for(Field fieldD : fields ) {
                fieldD.setAccessible(true);
                Object val = fieldD.get(dccUpdateUserReq);
                    if(null == val || "" == val) {
                        System.out.println("值为空");
                    }else{
                        //设置user对应的字段
                        Field declaredField = aClass1.getDeclaredField(fieldD.getName());
                        declaredField.setAccessible(true);
                        declaredField.set(dccUser,val);
                    }
            }
             dccUser.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
            dccUserService.update(dccUser);
            if (StringUtils.isAllEmpty(dccUpdateUserReq.getPasswod())){
                BeanUtil.copyProperties(dccUser,byId);
                StpUtil.getSession().set("user",byId);
            }else{
                StpUtil.logout();
            }

            return new ResponseEntity<>("重置成功",HttpStatus.OK);
    }



    @Log("客户登录")
    @ApiOperation("客户登录")
    @AnonymousAccess
    @GetMapping(value = "/loginDcc")
    public ResponseEntity<Object> loginDcc(String phone, String password) throws IOException {
        DccUserQueryCriteria dccUserQueryCriteria = new DccUserQueryCriteria();
        dccUserQueryCriteria.setPhone(phone);
        List<DccUserDto> dccUserDtos = dccUserService.queryAll(dccUserQueryCriteria);
        if (CollectionUtils.isEmpty(dccUserDtos)){
            return new ResponseEntity<>("登录失败,客户不存在！",HttpStatus.BAD_REQUEST);
        }else{
                DccUserDto dccUserDto = dccUserDtos.get(0);
                if (dccUserDto.getPasswod().equals(password)){
                    StpUtil.login(dccUserDto.getId());
                    StpUtil.getSession().set("user", dccUserDto);
                    return new ResponseEntity<>(StpUtil.getTokenInfo(),HttpStatus.OK);
                }else{
                    return new ResponseEntity<>("登录失败,密码错误！",HttpStatus.BAD_REQUEST);
                }
        }
    }

    @Log("获取token信息")
    @ApiOperation("获取token信息")
    @AnonymousAccess
    @GetMapping("/tokenInfo")
    public SaResult tokenInfo() {
        return SaResult.data(StpUtil.getTokenInfo());
    }



    @Log("客户状态查询")
    @ApiOperation("客户状态查询")
    @AnonymousAccess
    @GetMapping("/isLogin")
    public ResponseEntity<Object> isLogin() {
        return new ResponseEntity<>(StpUtil.isLogin(),HttpStatus.OK);

    }



    @Log("客户退出")
    @ApiOperation("客户退出")
    @AnonymousAccess
    @GetMapping(value = "/loginOut")
    public ResponseEntity<Object> loginOut(){
        StpUtil.logout();
        return new ResponseEntity<>("退出成功",HttpStatus.OK);
    }

}